<template>
  <a-modal
    :visible="visible"
    title="修改所属公司"
    :maskClosable="false"
    @cancel="closeModal"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-form layout="vertical">
      <a-form-item label="选择公司" v-bind="validateInfos.org_branch_id">
        <a-select
          v-model:value="modelRef.org_branch_id"
          :fieldNames="{
            label: 'company',
            value: 'id',
          }"
          :options="companyList"
          allowClear
          placeholder="请选择"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch, ref } from "vue";
import {Form, message, TreeSelect} from "ant-design-vue";
import request from "@/common/utils/request";
const useForm = Form.useForm;
import _ from "lodash";

export default defineComponent({
  name: "ChangeCompanyModal",
  components: {},
  props: {
    // 打开弹框
    visible: {
      type: Boolean,
      default: false,
    },
    billIds: {
      type: Array,
      default: () => {
        return [];
      },
    }
  },

  setup(props, { emit }) {
    const state = reactive({
      companyList: [],
      confirmLoading: false,
    });

    /**
     * @description: 表单字段
     */

    const modelRef = reactive({
      org_branch_id: undefined,
    });

    /**
     * @description: 验证规则
     */
    const requiredRule = [{ required: true, message: "必填项" }];
    const rulesRef = reactive({
      org_branch_id: requiredRule,
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );


    const closeModal = () => {
      emit("handleClose");
    };

    const handleSubmit = () => {
      validate().then(() => {
        state.confirmLoading = true;
        let params = {
          bill_ids: _.cloneDeep(props.billIds),
          org_branch_id: modelRef.org_branch_id,
        };
        request.post("/org", "/company/modifyBillBranch", params).then((res) => {
          message.success(res.msg || "保存成功！");
          state.confirmLoading = false;
          emit("handleSuccess");
        });
      });
    };

    const getCompanyList = () => {
      request.get("/org", "/company/orgAndBranch").then((res) => {
        state.companyList = res?.list || [];
      });
    };

    const init = () => {
      getCompanyList();
    };

    watch(
      () => props.visible,
      (visible) => {
        if (visible) {
          init();
        } else {
          resetFields();
          state.confirmLoading = false;
          state.companyList = [];
        }
      }
    );

    return {
      modelRef,
      resetFields,
      validateInfos,
      ...toRefs(state),
      closeModal,
      handleSubmit,
    };
  },
});
</script>

<style lang="less" scoped></style>
